<?php

use Elasticsearch\ClientBuilder;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

function genDownloadUrl($sourceFile, $fileName, $delete = false)
{
    $account = object_get(Auth::user(),'email');
    if($delete && $account && (Str::endsWith($fileName,'.xlsx') || Str::endsWith($fileName,'.xls'))) {
        (new ExcelWatermark(
            str_replace(['/', '\\'], DIRECTORY_SEPARATOR, storage_path("app/public/$sourceFile")),
            $account . '  ' .date('Y-m-d H:i:s'))
        )->setBgImg();
    }
    return \Illuminate\Support\Facades\Storage::url(\Illuminate\Support\Facades\Crypt::encryptString(json_encode(
        ['path'=>$sourceFile, 'name' => $fileName, 'delete' => $delete]
    )));
}
function genDownloadUrlByZip($sourceFile, $fileName)
{
    return \Illuminate\Support\Facades\Storage::url(\Illuminate\Support\Facades\Crypt::encryptString(json_encode(
        ['path'=>$sourceFile, 'name' => $fileName,'zip' => true,'delete' => true]
    )));
}

function getAppUrl(){
    if (preg_match("/cli/i", php_sapi_name())) {
        return env('APP_URL');
    } else {
        $url = $_SERVER['HTTP_X_FORWARDED_SCHEME'] ?? $_SERVER['REQUEST_SCHEME'];
        $url .= "://{$_SERVER['HTTP_HOST']}";
        if ($port = $_SERVER['HTTP_X_REAL_PORT'] ?? null) {
            if ($port != '80' && $port != '443') {
                $url .= ":{$_SERVER['HTTP_X_REAL_PORT']}";
            }
        }
        return $url.'/'.env('APP_NGINX_NAME','api-eam');
    }
}

function getCnsPmsUrl(){
    $scheme = dirname(trim(config('app.url'),'/'));
    if($scheme != 'http:' && $scheme != 'https:') {
        return dirname(trim(config('app.url'),'/'));
    } else {
        return config('app.url');
    }
}

function es(){
    return ClientBuilder::create()->setHosts([[
        'host' => config('database.connections.elasticsearch.host'),
        'port' => config('database.connections.elasticsearch.port'),
        'user' => config('database.connections.elasticsearch.username'),
        'pass' => config('database.connections.elasticsearch.password'),
        'scheme' => 'http',
    ]])->build();
}

function migrate_mv_index($index, callable $callable,$script = null)
{
    $indexBack = $index.'_migrate_'.time();
    es_mv_index($index, $indexBack,$callable,true, $script);
    es_mv_index($indexBack, $index,null,true);
    return $indexBack;
}


function es_mv_index($form,$to, callable $changeParams = null, $deleteForm = false, $script = null){
    $client = new \DesignMyNight\Elasticsearch\Connection(\Illuminate\Support\Facades\Config::get('database.connections.elasticsearch'));
    $mappings = \Illuminate\Support\Arr::get($client->indices()->getMapping(['index'=>$form]),$form);
    $settings = \Illuminate\Support\Arr::get($client->indices()->getSettings(['index'=>$form]),$form);
    $settings = ['settings'=>\Illuminate\Support\Arr::only(\Illuminate\Support\Arr::get($settings,'settings.index'),['number_of_shards','max_result_window','number_of_replicas','analysis'])];
    if($changeParams){
        $changeParams($mappings, $settings);
    }
    $created = \Illuminate\Support\Arr::get(es()->indices()->create(['index'=>$to,'body'=>array_merge($mappings,$settings)]),'acknowledged');
    if(!$created) {
        dump("create {$to} index Failed!!");
        return;
    }
    unset($settings['settings']['number_of_shards']);
    dump("create {$to} index ok");
    $reIndexParams = [
        'refresh' => true,'body' => ["conflicts" => "proceed",'source'=>['index'=>$form],'dest'=>['index'=>$to]]
    ];
    if($script) {
        $reIndexParams['body']['script'] = [
            "source" => $script, "lang" => "painless"
        ];
    }
    try{
        dump("reindex {$form} -> {$to} ".json_encode(\Illuminate\Support\Arr::except(es()->reindex($reIndexParams),[
                'throttled_until_millis','requests_per_second','throttled_millis','retries','noops','version_conflicts','batches'
            ])));
    }catch (\Throwable $e){
        dump("reindex {$form} -> {$to} index Failed!! ".$e->getMessage());
        return;
    }
    if($deleteForm) {
        if(!\Illuminate\Support\Arr::get(es()->indices()->delete(['index'=>$form]),'acknowledged')) {
            dump("delete {$form} index Failed!!");
            return;
        }
        dump("delete {$form} index ok");
    }
}

/**
 * 生成CSV文件
 * @param       $fileName
 * @param array $header
 * @param array $data
 */
function genCsvFile($fileName, array $header, array $data)
{

    // 打开文件资源，不存在则创建
    $fp = fopen(storage_path("app/public/{$fileName}.csv"),'a');
    // 写入表头
    fwrite($fp,implode(',', $header) . PHP_EOL);

    foreach ($data as $k => $v) {
        fwrite($fp,implode(',', $v) . PHP_EOL);
    }
    fclose($fp);
}

//组装字段

function getFiled($name){

    $list[] = '运营商';
    $list[] = '省份';
    $list[] = '资产名称';
    $list[] = '资产大类';
    $list[] = '资产标签';
    $list[] = '是否采用开源框架';
    $list[] = 'cpu厂商';
    $list[] = '内存厂商';
    $list[] = '交换芯片厂商';
    $list[] = '操作系统类型';
    $list[] = '硬件厂商';
    $list[] = '对外开放的端口';
    $list[] = 'web应用端口';
    $list[] = '中间件名称';
    $list[] = '中间件服务端口';
    $list[] = '数据库名称';
    $list[] = '数据库服务端口';
    $list[] = '是否可从互联网访问';
    $list[] = '资产状态';
    $list[] = '系统名称';
    $list[] = '网络单元类型';
    $list[] = '定级备案填报的定级对象名称';
    $list[] = '定级等级';
    $list[] = '网络位置';
    $list[] = '资产发现方式';
    $list[] = '资产发现时间';
    $list[] = '资产所在地区名称';

    if(in_array($name,['大于','大于等于','小于','小于等于','等于','不等于','区间','参照'])){
        if($name == '大于'){
            return '>';
        }elseif ('大于等于' == $name){
            return '>=';
        }elseif ('小于' == $name){
            return '<';
        }elseif ('小于等于' == $name){
            return '<=';
        }elseif ('等于' == $name){
            return '=';
        }elseif ('不等于' == $name){
            return '!=';
        }elseif ('区间' == $name){
            return 'between';
        }elseif ('参照' == $name){
            return 'in';
        }
    }elseif (in_array($name,$list)){
        if($name == '运营商'){
            return 'isp_code';
        }elseif ('省份' == $name){
            return 'city_code';
        }elseif ('资产名称' == $name){
            return 'asset_name';
        }elseif ('资产大类' == $name){
            return 'super_type';
        }elseif ('资产标签' == $name){
            return 'sub_type';
        }elseif ('是否采用开源框架' == $name){
            return 'open_source';
        }elseif ('cpu厂商' == $name){
            return 'cpu';
        }elseif ('内存厂商' == $name){
            return 'storage';
        }elseif ('交换芯片厂商' == $name){
            return 'chip';
        }elseif ('操作系统类型' == $name){
            return 'os';
        }elseif ('硬件厂商' == $name){
            return 'model';
        }elseif ('对外开放的端口' == $name){
            return 'port1';
        }elseif ('web应用端口' == $name){
            return 'port2';
        }elseif ('中间件名称' == $name){
            return 'middleware';
        }elseif ('中间件服务端口' == $name){
            return 'port4';
        }elseif ('数据库名称' == $name){
            return 'database';
        }elseif ('数据库服务端口' == $name){
            return 'port5';
        }elseif ('是否可从互联网访问' == $name){
            return 'is_access';
        }elseif ('资产状态' == $name){
            return 'state';
        }elseif ('系统名称' == $name){
            return 'system_name';
        }elseif ('网络单元类型' == $name){
            return 'network_unit';
        }elseif ('定级备案填报的定级对象名称' == $name){
            return 'object_name';
        }elseif ('定级等级' == $name){
            return 'device_level';
        }elseif ('网络位置' == $name){
            return 'net_position';
        }elseif ('资产发现方式' == $name){
            return 'found_type_list';
        }elseif ('资产发现时间' == $name){
            return 'found_type_time';
        }elseif ('资产所在地区名称' == $name){
            return 'location';
        }
    }else{
        return $name;
    }

}
function mysin2($whereText,$map,$i=0,$j=0){

    //处理输入的值转数字
    $map[2] = maptrans($map);
    //区分操作符号
    if($map[0] == '资产发现时间'){
        $map[2] = \Carbon\Carbon::parse($map[2]);
    }

    if(getFiled($map[0]) == 'port1' || getFiled($map[0]) == 'port2' || getFiled($map[0]) == 'port3' || getFiled($map[0]) == 'port4' || getFiled($map[0]) == 'port5'){

        $ccc = explode('port',getFiled($map[0]));
        $from = $ccc[1] ?? 0;
        $center['match_phrase']['port_flg']= $from;

        $whereText['bool']['must'][]= $center;
        $map[0] = 'port';
        if($map[1] == '等于'){
            if(getFiled($map[0]) == 'super_type'){
                if(!is_array($map[2])){
                    $map[2] = [$map[2]];
                }
                $whereText['bool']['must'][]['terms'][getFiled($map[0])] = $map[2];
            }else{
                $whereText['bool']['must'][]['term'][getFiled($map[0])] = $map[2];
            }
        }elseif ($map[1] == '不等于'){
            $whereText['bool']['must_not'][]['term'][getFiled($map[0])] = $map[2];
        }elseif ($map[1] == '区间'){
            $bet['range'][getFiled($map[0])]['gte'] = $map[2][0];
            $bet['range'][getFiled($map[0])]['lte'] = $map[2][1] ?? '';
            $whereText['bool']['must'][] = $bet;
        }elseif ($map[1] == '参照'){
            $whereText['bool']['must'][]['terms'][getFiled($map[0])]= $map[2];
        }

    }elseif (in_array(getFiled($map[0]),['cpu','os','chip','model','storage','middleware','database'])){
        $field = 'maker';
        if(getFiled($map[0]) == 'database' || getFiled($map[0]) == 'middleware'){
            $field ='name';
        }
        if(getFiled($map[0]) == 'os'){
            $field ='type';
        }
        if($i > 0){
            if($j == 0){
                $centeri = $whereText['bool']['must'] ?? $whereText['bool']['should'];
                $center2['nested']['path'] = getFiled($map[0]);
                $center2['nested']['query']['bool']['must']['match_phrase'][getFiled($map[0]).'.'.$field.'.keyword']= $map[2];
                $a['bool']['must'][] = $center2;
                $centeri[] =$a;
                if(isset($whereText['bool']['must'])){
                    $whereText['bool']['must'] = $centeri;
                }else{
                    $whereText['bool']['should'] = $centeri;
                }
            }else{
                $center2['nested']['path'] = getFiled($map[0]);
                $center2['nested']['query']['bool']['must']['match_phrase'][getFiled($map[0]).'.'.$field.'.keyword']= $map[2];
                $a['bool']['must'][] = $center2;
                if(isset($whereText['bool']['must'])){
                    $whereText[count($whereText['bool']['must'])]['bool']['must'][] = $a;
                }else{
                    $ccc = $whereText['bool']['should'][array_key_last($whereText['bool']['should'])];
                    $ccc['bool']['must'][]['nested']['path'] = getFiled($map[0]);
                    $ccc['bool']['must'][]['nested']['query']['bool']['must']['match_phrase'][getFiled($map[0]).'.'.$field.'.keyword']= $map[2];
                    $whereText['bool']['should'][array_key_last($whereText['bool']['should'])] = $ccc;
                }
            }
        }else{
            $center2['nested']['path'] = getFiled($map[0]);
            $center2['nested']['query']['bool']['must']['match_phrase'][getFiled($map[0]).'.'.$field.'.keyword']= $map[2];
            $whereText['bool']['must'][]= $center2;
        }

    }else{

        if($map[1] == '等于'){
            if(getFiled($map[0]) == 'super_type'){
                if(!is_array($map[2])){
                    $map[2] = [$map[2]];
                }
                if($i > 0){
                    if($j == 0){
                        $centeri = $whereText['bool']['must'] ?? $whereText['bool']['should'];
                        $a['bool']['must'][]['terms'][getFiled($map[0])] = $map[2];
                        $centeri[] =$a;
                        if(isset($whereText['bool']['must'])){
                            $whereText['bool']['must'] = $centeri;
                        }else{
                            $whereText['bool']['should'] = $centeri;
                        }
                    }else{
                        $a['bool']['must'][]['terms'][getFiled($map[0])] = $map[2];
                        if(isset($whereText['bool']['must'])){
                            $whereText[count($whereText['bool']['must'])]['bool']['must'][] = $a;
                        }else{
                            $ccc = $whereText['bool']['should'][array_key_last($whereText['bool']['should'])];
                            $ccc['bool']['must'][]['terms'][getFiled($map[0])] = $map[2];
                            $whereText['bool']['should'][array_key_last($whereText['bool']['should'])] = $ccc;
                        }
                    }
                }else{
                    $whereText['bool']['must'][]['terms'][getFiled($map[0])] = $map[2];
                }
            }else{
                if($i > 0){
                    if($j == 0){
                        $centeri = $whereText['bool']['must'] ?? $whereText['bool']['should'];
                        $a['bool']['must'][]['term'][getFiled($map[0])] = $map[2];
                        $centeri[] =$a;
                        if(isset($whereText['bool']['must'])){
                            $whereText['bool']['must'] = $centeri;
                        }else{
                            $whereText['bool']['should'] = $centeri;
                        }
                    }else{
                        $a['bool']['must'][]['term'][getFiled($map[0])] = $map[2];
                        if(isset($whereText['bool']['must'])){
                            $whereText[count($whereText['bool']['must'])]['bool']['must'][] = $a;
                        }else{
                            $ccc = $whereText['bool']['should'][array_key_last($whereText['bool']['should'])];
                            $ccc['bool']['must'][]['term'][getFiled($map[0])] = $map[2];
                            $whereText['bool']['should'][array_key_last($whereText['bool']['should'])] = $ccc;
                        }
                    }
                }else{
                    $whereText['bool']['must'][]['term'][getFiled($map[0])] = $map[2];
                }
            }
        }elseif ($map[1] == '不等于'){
            if($i > 0){
                if($j == 0){
                    $centeri = $whereText['bool']['must_not'] ?? $whereText['bool']['should'];
                    $a['bool']['must_not'][]['term'][getFiled($map[0])] = $map[2];
                    $centeri[] =$a;
                    if(isset($whereText['bool']['must_not'])){
                        $whereText['bool']['must_not'] = $centeri;
                    }else{
                        $whereText['bool']['should'] = $centeri;
                    }
                }else{
                    $a['bool']['must_not'][]['term'][getFiled($map[0])] = $map[2];
                    if(isset($whereText['bool']['must_not'])){
                        $whereText[count($whereText['bool']['must_not'])]['bool']['must_not'][] = $a;
                    }else{
                        $ccc = $whereText['bool']['should'][array_key_last($whereText['bool']['should'])];
                        $ccc['bool']['must_not'][]['term'][getFiled($map[0])] = $map[2];
                        $whereText['bool']['should'][array_key_last($whereText['bool']['should'])] = $ccc;
                    }
                }
            }else{
                $whereText['bool']['must_not'][]['term'][getFiled($map[0])] = $map[2];
            }

        }elseif ($map[1] == '大于'){
            if($i > 0){
                if($j == 0){
                    $centeri = $whereText['bool']['must'] ?? $whereText['bool']['should'];
                    $a['bool']['must'][]['range'][getFiled($map[0])]['gt'] = $map[2];
                    $centeri[] =$a;
                    if(isset($whereText['bool']['must'])){
                        $whereText['bool']['must'] = $centeri;
                    }else{
                        $whereText['bool']['should'] = $centeri;
                    }
                }else{
                    $a['bool']['must'][]['range'][getFiled($map[0])]['gt']= $map[2];
                    if(isset($whereText['bool']['must'])){
                        $whereText[count($whereText['bool']['must'])]['bool']['must'][] = $a;
                    }else{
                        $ccc = $whereText['bool']['should'][array_key_last($whereText['bool']['should'])];
                        $ccc['bool']['must'][]['range'][getFiled($map[0])]['gt']= $map[2];
                        $whereText['bool']['should'][array_key_last($whereText['bool']['should'])] = $ccc;
                    }
                }
            }else{
                $whereText['bool']['must'][]['term'][getFiled($map[0])]['gt'] = $map[2];
            }
        }elseif ($map[1] == '大于等于'){
            if($i > 0){
                if($j == 0){
                    $centeri = $whereText['bool']['must'] ?? $whereText['bool']['should'];
                    $a['bool']['must'][]['range'][getFiled($map[0])]['gte'] = $map[2];
                    $centeri[] =$a;
                    if(isset($whereText['bool']['must'])){
                        $whereText['bool']['must'] = $centeri;
                    }else{
                        $whereText['bool']['should'] = $centeri;
                    }
                }else{
                    $a['bool']['must'][]['range'][getFiled($map[0])]['gte']= $map[2];
                    if(isset($whereText['bool']['must'])){
                        $whereText[count($whereText['bool']['must'])]['bool']['must'][] = $a;
                    }else{
                        $ccc = $whereText['bool']['should'][array_key_last($whereText['bool']['should'])];
                        $ccc['bool']['must'][]['range'][getFiled($map[0])]['gte']= $map[2];
                        $whereText['bool']['should'][array_key_last($whereText['bool']['should'])] = $ccc;
                    }
                }
            }else{
                $whereText['bool']['must'][]['term'][getFiled($map[0])]['gte'] = $map[2];
            }

        }elseif ($map[1] == '小于'){
            if($i > 0){
                if($j == 0){
                    $centeri = $whereText['bool']['must'] ?? $whereText['bool']['should'];
                    $a['bool']['must'][]['range'][getFiled($map[0])]['lt'] = $map[2];
                    $centeri[] =$a;
                    if(isset($whereText['bool']['must'])){
                        $whereText['bool']['must'] = $centeri;
                    }else{
                        $whereText['bool']['should'] = $centeri;
                    }
                }else{
                    $a['bool']['must'][]['range'][getFiled($map[0])]['lt']= $map[2];
                    if(isset($whereText['bool']['must'])){
                        $whereText[count($whereText['bool']['must'])]['bool']['must'][] = $a;
                    }else{
                        $ccc = $whereText['bool']['should'][array_key_last($whereText['bool']['should'])];
                        $ccc['bool']['must'][]['range'][getFiled($map[0])]['lt']= $map[2];
                        $whereText['bool']['should'][array_key_last($whereText['bool']['should'])] = $ccc;
                    }
                }
            }else{
                $whereText['bool']['must'][]['term'][getFiled($map[0])]['lt'] = $map[2];
            }
        }elseif ($map[1] == '小于等于'){
            if($i > 0){
                if($j == 0){
                    $centeri = $whereText['bool']['must'] ?? $whereText['bool']['should'];
                    $a['bool']['must'][]['range'][getFiled($map[0])]['lte'] = $map[2];
                    $centeri[] =$a;
                    if(isset($whereText['bool']['must'])){
                        $whereText['bool']['must'] = $centeri;
                    }else{
                        $whereText['bool']['should'] = $centeri;
                    }
                }else{
                    $a['bool']['must'][]['range'][getFiled($map[0])]['lte']= $map[2];
                    if(isset($whereText['bool']['must'])){
                        $whereText[count($whereText['bool']['must'])]['bool']['must'][] = $a;
                    }else{
                        $ccc = $whereText['bool']['should'][array_key_last($whereText['bool']['should'])];
                        $ccc['bool']['must'][]['range'][getFiled($map[0])]['lte']= $map[2];
                        $whereText['bool']['should'][array_key_last($whereText['bool']['should'])] = $ccc;
                    }
                }
            }else{
                $whereText['bool']['must'][]['term'][getFiled($map[0])]['lte'] = $map[2];
            }
        }elseif ($map[1] == '区间'){

            if($i > 0){
                if($j == 0){
                    $centeri = $whereText['bool']['must'] ?? $whereText['bool']['should'];
                    $bet['range'][getFiled($map[0])]['gte'] = $map[2][0];
                    $bet['range'][getFiled($map[0])]['lte'] = $map[2][1] ?? '';
                    $a['bool']['must'][] = $bet;
                    $centeri[] =$a;
                    if(isset($whereText['bool']['must'])){
                        $whereText['bool']['must'] = $centeri;
                    }else{
                        $whereText['bool']['should'] = $centeri;
                    }
                }else{
                    $bet['range'][getFiled($map[0])]['gte'] = $map[2][0];
                    $bet['range'][getFiled($map[0])]['lte'] = $map[2][1] ?? '';
                    $a['bool']['must'][] = $bet;
                    if(isset($whereText['bool']['must'])){
                        $whereText[count($whereText['bool']['must'])]['bool']['must'][] = $a;
                    }else{
                        $ccc = $whereText['bool']['should'][array_key_last($whereText['bool']['should'])];
                        $ccc['bool']['must'][]['range'][getFiled($map[0])]['gte'] = $map[2][0];
                        $ccc['bool']['must'][]['range'][getFiled($map[0])]['lte'] = $map[2][1];
                        $whereText['bool']['should'][array_key_last($whereText['bool']['should'])] = $ccc;
                    }
                }
            }else{
                $bet['range'][getFiled($map[0])]['gte'] = $map[2][0];
                $bet['range'][getFiled($map[0])]['lte'] = $map[2][1] ?? '';
                $whereText['bool']['must'][] = $bet;
            }
        }elseif ($map[1] == '参照'){
            if($i > 0){
                if($j == 0){
                    $centeri = $whereText['bool']['must'] ?? $whereText['bool']['should'];
                    $a['bool']['must'][]['terms'][getFiled($map[0])] = $map[2];
                    $centeri[] =$a;
                    if(isset($whereText['bool']['must'])){
                        $whereText['bool']['must'] = $centeri;
                    }else{
                        $whereText['bool']['should'] = $centeri;
                    }
                }else{
                    $a['bool']['must'][]['terms'][getFiled($map[0])] = $map[2];
                    if(isset($whereText['bool']['must'])){
                        $whereText[count($whereText['bool']['must'])]['bool']['must'][] = $a;
                    }else{
                        $ccc = $whereText['bool']['should'][array_key_last($whereText['bool']['should'])];
                        $ccc['bool']['must'][]['terms'][getFiled($map[0])] = $map[2];
                        $whereText['bool']['should'][array_key_last($whereText['bool']['should'])] = $ccc;
                    }
                }
            }else{
                $whereText['bool']['must'][]['terms'][getFiled($map[0])] = $map[2];
            }
        }
    }
    return $whereText;
}
function mysin($whereText,$map){

    //处理输入的值转数字
    $map[2] = maptrans($map);
    //区分操作符号
    if($map[0] == '资产发现时间'){
        $map[2] = \Carbon\Carbon::parse($map[2]);
    }

    if(getFiled($map[0]) == 'port1' || getFiled($map[0]) == 'port2' || getFiled($map[0]) == 'port3' || getFiled($map[0]) == 'port4' || getFiled($map[0]) == 'port5'){
        $ccc = explode('port',getFiled($map[0]));
        $from = $ccc[1] ?? 0;
        $center['match_phrase']['port_flg']= $from;
        $whereText['bool']['must'][]= $center;
        $map[0] = 'port';
        if($map[1] == '等于'){
            if(getFiled($map[0]) == 'super_type'){
                if(!is_array($map[2])){
                    $map[2] = [$map[2]];
                }
                $whereText['bool']['must'][]['terms'][getFiled($map[0])] = $map[2];
            }else{
                $whereText['bool']['must'][]['term'][getFiled($map[0])] = $map[2];
            }
        }elseif ($map[1] == '不等于'){
            $whereText['bool']['must_not'][]['term'][getFiled($map[0])] = $map[2];
        }elseif ($map[1] == '大于'){
            $whereText['bool']['must'][]['range'][getFiled($map[0])]['gt'] = $map[2];
        }elseif ($map[1] == '大于等于'){
            $whereText['bool']['must'][]['range'][getFiled($map[0])]['gte'] = $map[2];
        }elseif ($map[1] == '小于'){
            $whereText['bool']['must'][]['range'][getFiled($map[0])]['lt'] = $map[2];
        }elseif ($map[1] == '小于等于'){
            $whereText['bool']['must'][]['range'][getFiled($map[0])]['lte'] = $map[2];
        }elseif ($map[1] == '区间'){
            $bet['range'][getFiled($map[0])]['gte'] = $map[2][0];
            $bet['range'][getFiled($map[0])]['lte'] = $map[2][1] ?? '';
            $whereText['bool']['must'][] = $bet;
        }elseif ($map[1] == '参照'){
            $whereText['bool']['must'][]['terms'][getFiled($map[0])]= $map[2];
        }
    }elseif (in_array(getFiled($map[0]),['cpu','os','chip','model','storage','middleware','database'])){
        $field = 'maker';
        if(getFiled($map[0]) == 'database' || getFiled($map[0]) == 'middleware'){
            $field ='name';
        }
        if(getFiled($map[0]) == 'os'){
            $field ='type';
        }
        $center2['nested']['path'] = getFiled($map[0]);
        $center2['nested']['query']['bool']['must']['match_phrase'][getFiled($map[0]).'.'.$field.'.keyword']= $map[2];
        $whereText['bool']['must'][]= $center2;
    }else{
        if($map[1] == '等于'){
            if(getFiled($map[0]) == 'super_type'){
                if(!is_array($map[2])){
                    $map[2] = [$map[2]];
                }
                $whereText['bool']['must'][]['terms'][getFiled($map[0])] = $map[2];
            }else{
                $whereText['bool']['must'][]['term'][getFiled($map[0])] = $map[2];
            }
        }elseif ($map[1] == '不等于'){
            $whereText['bool']['must_not'][]['term'][getFiled($map[0])] = $map[2];
        }elseif ($map[1] == '大于'){
            $whereText['bool']['must'][]['range'][getFiled($map[0])]['gt'] = $map[2];
        }elseif ($map[1] == '大于等于'){
            $whereText['bool']['must'][]['range'][getFiled($map[0])]['gte'] = $map[2];
        }elseif ($map[1] == '小于'){
            $whereText['bool']['must'][]['range'][getFiled($map[0])]['lt'] = $map[2];
        }elseif ($map[1] == '小于等于'){
            $whereText['bool']['must'][]['range'][getFiled($map[0])]['lte'] = $map[2];
        }elseif ($map[1] == '区间'){
            $bet['range'][getFiled($map[0])]['gte'] = $map[2][0];
            $bet['range'][getFiled($map[0])]['lte'] = $map[2][1] ?? '';
            $whereText['bool']['must'][] = $bet;
        }elseif ($map[1] == '参照'){
            $whereText['bool']['must'][]['terms'][getFiled($map[0])]= $map[2];
        }
    }
    return $whereText;
}


function myorsin($whereText,$map){


    //处理输入的值转数字
    $map[2] = maptrans($map);
    //区分操作符号
    if($map[0] == '资产发现时间'){
        $map[2] = \Carbon\Carbon::parse($map[2]);
    }

    if(getFiled($map[0]) == 'port1' || getFiled($map[0]) == 'port2' || getFiled($map[0]) == 'port3' || getFiled($map[0]) == 'port4' || getFiled($map[0]) == 'port5'){

        $ccc = explode('port',getFiled($map[0]));
        $from = $ccc[1] ?? 0;
        $center['match_phrase']['port_flg']= $from;
        $whereText['bool']['should'][]= $center;
        $map[0] = 'port';
        if($map[1] == '等于'){
            if(getFiled($map[0]) == 'super_type'){
                if(!is_array($map[2])){
                    $map[2] = [$map[2]];
                }
                $whereText['bool']['should'][]['terms'][getFiled($map[0])] = $map[2];
            }else{
                $whereText['bool']['should'][]['term'][getFiled($map[0])] = $map[2];
            }
        }elseif ($map[1] == '不等于'){
            $whereText['bool']['must_not'][]['term'][getFiled($map[0])] = $map[2];
        }elseif ($map[1] == '大于'){
            $whereText['bool']['should'][]['range'][getFiled($map[0])]['gt'] = $map[2];
        }elseif ($map[1] == '大于等于'){
            $whereText['bool']['should'][]['range'][getFiled($map[0])]['gte'] = $map[2];
        }elseif ($map[1] == '小于'){
            $whereText['bool']['should'][]['range'][getFiled($map[0])]['lt'] = $map[2];
        }elseif ($map[1] == '小于等于'){
            $whereText['bool']['should'][]['range'][getFiled($map[0])]['lte'] = $map[2];
        }elseif ($map[1] == '区间'){
            $bet['range'][getFiled($map[0])]['gte'] = $map[2][0];
            $bet['range'][getFiled($map[0])]['lte'] = $map[2][1] ?? '';
            $whereText['bool']['should'][] = $bet;
        }elseif ($map[1] == '参照'){
            $whereText['bool']['should'][]['terms'][getFiled($map[0])]= $map[2];
        }
    }elseif (in_array(getFiled($map[0]),['cpu','os','chip','model','storage','middleware','database'])){
        $field = 'maker';
        if(getFiled($map[0]) == 'database' || getFiled($map[0]) == 'middleware'){
            $field ='name';
        }
        if(getFiled($map[0]) == 'os'){
            $field ='type';
        }
        $center2['nested']['path'] = getFiled($map[0]);
        $center2['nested']['query']['bool']['must']['match_phrase'][getFiled($map[0]).'.'.$field.'.keyword']= $map[2];
        $whereText['bool']['should'][]= $center2;
    }else{
        if($map[1] == '等于'){
            if(getFiled($map[0]) == 'super_type'){
                if(!is_array($map[2])){
                    $map[2] = [$map[2]];
                }
                $whereText['bool']['should'][]['terms'][getFiled($map[0])] = $map[2];
            }else{
                $whereText['bool']['should'][]['term'][getFiled($map[0])] = $map[2];
            }
        }elseif ($map[1] == '不等于'){
            $whereText['bool']['must_not'][]['term'][getFiled($map[0])] = $map[2];
        }elseif ($map[1] == '大于'){
            $whereText['bool']['should'][]['range'][getFiled($map[0])]['gt'] = $map[2];
        }elseif ($map[1] == '大于等于'){
            $whereText['bool']['should'][]['range'][getFiled($map[0])]['gte'] = $map[2];
        }elseif ($map[1] == '小于'){
            $whereText['bool']['should'][]['range'][getFiled($map[0])]['lt'] = $map[2];
        }elseif ($map[1] == '小于等于'){
            $whereText['bool']['should'][]['range'][getFiled($map[0])]['lte'] = $map[2];
        }elseif ($map[1] == '区间'){
            $bet['range'][getFiled($map[0])]['gte'] = $map[2][0];
            $bet['range'][getFiled($map[0])]['lte'] = $map[2][1] ?? '';
            $whereText['bool']['should'][] = $bet;
        }elseif ($map[1] == '参照'){
            $whereText['bool']['should'][]['terms'][getFiled($map[0])]= $map[2];
        }
    }
    return $whereText;
}


function maptrans($map){
    if(in_array($map[2],['是','否','不可以','可以','下线','在网','停用','删除','内网','外网','远程扫描','WEB爬虫','网络流量分析','日志分析','Agent','登录资产','手动导入','其他'])){
        if(in_array($map[2],['是','不可以','在网','内网','远程扫描'])){
            $map[2] =0;
        }elseif (in_array($map[2],['否','可以','下线','外网','WEB爬虫'])){
            $map[2] =1;
        }elseif (in_array($map[2],['停用','网络流量分析'])){
            $map[2] =2;
        }elseif ($map[2] == '日志分析'){
            $map[2] =3;
        }elseif ($map[3] == 'Agent'){
            $map[2] =4;
        }elseif ($map[4] == '登录资产'){
            $map[2] =5;
        }elseif ($map[5] == '手动导入'){
            $map[2] =6;
        }else{
            $map[2] =7;
        }
    }
    return $map[2];
}

function getExportField($arr){

    $data['运营商'] = 'isp_code';
    $data['省份'] = 'city_code';
    $data['资产名称'] = 'asset_name';
    $data['资产大类'] = 'super_type';
    $data['资产标签'] = 'sub_type';
    $data['是否采用开源框架'] = 'sub_type';
    $data['cpu厂商'] = 'cpu';
    $data['内存厂商'] = 'storage';
    $data['交换芯片厂商'] = 'chip';
    $data['操作系统类型'] = 'os';
    $data['硬件厂商'] = 'model';
    $data['对外开放的端口'] = 'port1';
    $data['web应用端口'] = 'port2';
    $data['中间件名称'] = 'middleware';
    $data['中间件服务端口'] = 'port3';
    $data['数据库名称'] = 'database';
    $data['数据库服务端口'] = 'port4';
    $data['是否可从互联网访问'] = 'is_access';
    $data['资产状态'] = 'state';
    $data['系统名称'] = 'system_name';
    $data['网络单元类型'] = 'network_unit';
    $data['定级备案填报的定级对象名称'] = 'object_name';
    $data['定级等级'] = 'device_level';
    $data['网络位置'] = 'net_position';
    $data['资产发现方式'] = 'found_type_list';
    $data['资产发现时间'] = 'found_type_time';
    $data['资产所在地区名称'] = 'location';

    $return =[];
    foreach ($arr as $v){
        if(isset($data[$v])){
            $return[] = $data[$v];
        }
    }

    return array_unique($return);

}


function open_source($type){

    if(0 == $type){
        return '是';
    }else{
        return '否';
    }
}

function is_access($type){
    if(0 == $type){
        return '不可以';
    }else{
        return '可以';
    }
}

function state($type){
    if(0 == $type){
        return '在网';
    }elseif(1 == $type){
        return '下线';
    }elseif(2 == $type){
        return '停用';
    }elseif(3 == $type){
        return '删除';
    }
}

function net_position($type){
    if(0 == $type){
        return '内网';
    }else{
        return '外网';
    }
}

function found_type_list($type){
    if(0 == $type){
        return '远程扫描';
    }elseif(1 == $type){
        return 'WEB爬虫';
    }elseif(2 == $type){
        return '网络流量分析';
    }elseif(3 == $type){
        return '日志分析';
    }elseif(4 == $type){
        return 'Agent';
    }elseif(5 == $type){
        return '登录资产';
    }elseif(6 == $type){
        return '手动导入';
    }elseif(7 == $type){
        return '其他';
    }
}

function objectToArray($object)
{
    //先编码成json字符串，再解码成数组
    return json_decode(json_encode($object), true);
}
function fullRangeIpStr($ip){
    if(!filter_var($ip, FILTER_VALIDATE_IP)){
        $ipRange =  explode('-',$ip);
        if(!empty($ipRange[1] ?? null) && !filter_var($ipRange[1] ?? '', FILTER_VALIDATE_IP) && filter_var($ipRange[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            $first = substr($ipRange[0], 0, strrpos($ipRange[0], "."));
            $ipRange[1] = "{$first}.{$ipRange[1]}";
            return implode('-',$ipRange);
        }
    }
    return $ip;
}

//获取定级备案数据
function getCnsData($name){

    if(empty($name)){
        return [];
    }

    try {
        $info =[];

        $infoObject = \App\Models\CnsPms\ObjectRecord::query()->with(['nete','districts'])->where('name',$name)->first();
        if(empty($infoObject)){
            $infoObject = \App\Models\CnsPms\ObjectRecord::query()->with(['nete','districts'])->where('name',$name.' ')->first();
            if(empty($infoObject)){
                $infoObject = \App\Models\CnsPms\ObjectRecord::query()->with(['nete','districts'])->where('name',' '.$name.' ')->first();
                if(empty($infoObject)){
                    $infoObject = \App\Models\CnsPms\ObjectRecord::query()->with(['nete','districts'])->where('name',' '.$name)->first();
                    if(empty($infoObject)){
                        $infoObject = \App\Models\CnsPms\ObjectRecord::query()->with(['nete','districts'])->where('name','like','%'.$name.'%')->first();
                    }
                }
            }
        }

        if($infoObject){
            $info = $infoObject->toArray();
        }


        $return =[];
        $neteArr = [

            [
                'name' => '固定通信网',
                'code' => '100001'
            ], [
                'name' => '移动通信网',
                'code' => '100002'
            ], [
                'name' => '增值业务网-消息网',
                'code' => '100003'
            ], [
                'name' => '增值业务网-智能网',
                'code' => '100004'
            ], [
                'name' => '接入网',
                'code' => '100005'
            ], [
                'name' => '传送网',
                'code' => '100006'
            ], [
                'name' => 'IP承载网',
                'code' => '100007'
            ], [
                'name' => '信令网',
                'code' => '100008'
            ], [
                'name' => '同步网',
                'code' => '100009'
            ], [
                'name' => '支撑网',
                'code' => '100010'
            ], [
                'name' => '非核心生产单元',
                'code' => '100011'
            ], [
                'name' => '网上营业厅',
                'code' => '100012'
            ], [
                'name' => '域名服务系统',
                'code' => '100013'
            ], [
                'name' => '互联网数据中心',
                'code' => '100014'
            ], [
                'name' => '互联网接入服务系统',
                'code' => '100015'
            ], [
                'name' => '互联网云服务平台',
                'code' => '100016'
            ], [
                'name' => '互联网内容分发网络',
                'code' => '100017'
            ], [
                'name' => '移动互联网联网应用',
                'code' => '100018'
            ], [
                'name' => '移动定位系统',
                'code' => '100019'
            ], [
                'name' => '信息服务业务系统',
                'code' => '100020'
            ], [
                'name' => 'WAP网关系统',
                'code' => '100021'
            ], [
                'name' => '大数据平台',
                'code' => '100022'
            ], [
                'name' => '集中化安全管理系统',
                'code' => '100023'
            ], [
                'name' => 'IPTV平台',
                'code' => '100024'
            ], [
                'name' => 'RCS融合通信平台',
                'code' => '100025'
            ], [
                'name' => '融合网络',
                'code' => '100026'
            ], [
                'name' => '物联网平台',
                'code' => '100027'
            ], [
                'name' => '其他',
                'code' => '199999'
            ]

        ];

        if($info){

            $return['network_unit'] ='';
            $nete_name = $info['nete']['name'] ?? '';
            if($nete_name){
                //判断是否是1级网元
                $level = $info['nete']['level'] ?? '';
                if($level == 1){
                    foreach ($neteArr as $arr){
                        if($arr['name'] == $nete_name){
                            $return['network_unit'] = $arr['code'];
                        }
                    }
                }elseif (2 == $level){

                    $neteId = $info['nete']['parent_id'] ?? '';
                    $thisNete = \App\Models\CnsPms\Nete::query()->where('id',$neteId)->first();

                    if($thisNete){
                        if($thisNete->level == 1){
                            foreach ($neteArr as $arr){
                                if($arr['name'] == $thisNete->name){
                                    $return['network_unit'] = $arr['code'];
                                }
                            }
                        }
                    }else{
                        $return['network_unit'] = '';
                    }

                }elseif (3 == $level){
                    $neteId = $info['nete']['parent_id'] ?? '';
                    $thisNete = \App\Models\CnsPms\Nete::query()->where('id',$neteId)->first();
                    $neteIdTop = $thisNete->parent_id ?? '';
                    $thisNeteTop = \App\Models\CnsPms\Nete::query()->where('id',$neteIdTop)->first();
                    if($thisNeteTop){
                        if($thisNeteTop->level == 1){
                            foreach ($neteArr as $arr){
                                if($arr['name'] == $thisNeteTop->name){
                                    $return['network_unit'] = $arr['code'];
                                }
                            }
                        }
                    }else{
                        $return['network_unit'] = '';
                    }
                }else{
                    $return['network_unit'] = '';
                }
            }
            $return['isp_code'] = '';
            $return['city_code'] = $info['districts']['administrative_divisions'] ?? '';
            //查找运营商代码
            $company_id = $info['company_id'] ?? '';

            if($company_id){
                $org = \App\Models\CnsPms\Company::query()->with('org')->where('id',$company_id)->first()->toArray();
                $parent_id = $org['org']['parent_id'] ?? '';
                if($parent_id){
                    if($parent_id == 6 || $parent_id == 7 || $parent_id == 8){
                        //判断是否还有父级
                        $org2 = \App\Models\CnsPms\Company::query()->with('org')->where('id',$parent_id)->where('type',3)->first();
                        if($org2){
                            $parent_id2 = $org2['org']['parent_id'];
                            if($parent_id2 == 6 || $parent_id2 == 7 || $parent_id2 == 8){
                                if($parent_id2 ==6){
                                    $return['isp_code'] = 'CUCC';
                                }elseif (8 == $parent_id2){
                                    $return['isp_code'] = 'CTC';
                                }else{
                                    $return['isp_code'] = 'CMCC';
                                }
                            }else{
                                //暂时不写三层级的判断
                                $return['isp_code'] = '';
                            }

                        }else{
                            if($parent_id ==6){
                                $return['isp_code'] = 'CUCC';
                            }elseif (8 == $parent_id){
                                $return['isp_code'] = 'CTC';
                            }else{
                                $return['isp_code'] = 'CMCC';
                            }
                        }
                    }
                }
            }
            $return['location'] = $info['city_name'] ?? '';
        }

        return $return;
    }catch (\Throwable $e){
        Log::info('错误的定级对象数据查询,定级对象名称：'.$name);
        Log::info($e->getMessage(),$e->getTrace());
        return [];
    }



}

